package com.easy.controller;

import com.easy.bean.User;
import com.easy.common.CommonResult;
import com.easy.config.ImgStaticPathConfig;
import com.easy.dao.IUserDao;
import com.easy.service.IUserService;
import com.easy.util.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService is;
    @Autowired
    IUserDao dao;

    // 修改密码
    @PutMapping("/editpassword")
    public CommonResult changePassword(@RequestBody User user) {
        boolean isUpdated = is.updateUser(user.getId(), user.getOldPassword(), user.getNewPassword());
        if (isUpdated) {
            return CommonResult.success("密码修改成功");
        } else {
            return CommonResult.fail("旧密码错误或更新失败");
        }
    }


    //  上传头像
    @PutMapping("img")
    public CommonResult userImg(@RequestParam("head_image") MultipartFile file){
        System.out.println(file);
        String newName = UploadFileUtil.uploadFile(file);
        return CommonResult.success(ImgStaticPathConfig.STATIC_PATH + newName );
    }
    // 上传修改头像
    @PostMapping("/img/{id}")
    public CommonResult postImageId(@RequestParam("head_image") MultipartFile file, @PathVariable int id) {
        String newName = UploadFileUtil.uploadFile(file);
        return CommonResult.success(ImgStaticPathConfig.STATIC_PATH+newName);
    }

    // 上传修改头像
    @PostMapping("/image/{id}")
    public CommonResult postImage(@RequestParam("head_image") MultipartFile file, @PathVariable int id) {
        // 输入验证
        if (file.isEmpty() || !file.getContentType().startsWith("image/")) {
            return CommonResult.fail("Invalid file. Please upload an image.");
        }
        // 存储文件
        String newFileName = UploadFileUtil.uploadFile(file);
        // 获取用户信息
        User user = dao.getUserById(id);
        if (user == null) {
            return CommonResult.fail("User not found");
        }
        // 更新用户的头像路径
        user.setHead_image(newFileName);
        int count = dao.editUser(user);

        // 返回上传文件的地址或者用户信息
        if (count > 0) {
            return CommonResult.success(user);
        } else {
            return CommonResult.fail("Failed to update user image");
        }
    }
    // 查看头像
    @GetMapping("/image/{id}")
    public ResponseEntity<byte[]> getImage(@PathVariable int id) {
        User user = dao.getUserById(id);
        if (user == null || user.getHead_image() == null) {
            return ResponseEntity.notFound().build();
        }

        // 从数据库中获取文件名（包含后缀名）
        String fileName = user.getHead_image();
        String imagePath = "D:\\Desktop\\mycode\\java\\myWarehouse\\src\\main\\resources\\images\\" + fileName;
        Path path = Paths.get(imagePath);
        if (!Files.exists(path)) {
            return ResponseEntity.notFound().build();
        }

        try {
            byte[] imageBytes = Files.readAllBytes(path);

            // 通过文件名获取文件扩展名
            String extension = com.google.common.io.Files.getFileExtension(fileName);
            MediaType mediaType;
            switch (extension.toLowerCase()) {
                case "png":
                    mediaType = MediaType.IMAGE_PNG;
                    break;
                case "jpg":
                case "jpeg":
                    mediaType = MediaType.IMAGE_JPEG;
                    break;
                case "gif":
                    mediaType = MediaType.IMAGE_GIF;
                    break;
                default:
                    mediaType = MediaType.APPLICATION_OCTET_STREAM;
            }

            return ResponseEntity.ok()
                    .contentType(mediaType)
                    .body(imageBytes);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }


    // 获取当前用户的信息
    @GetMapping("/getusername")
    public CommonResult getCurrentUser(User user) {
        user = is.getCurrentUser(user.getUser_name());
        if (user != null) {
            return CommonResult.success(user);
        } else {
            return CommonResult.fail("User not found");
        }
    }

    // 获取当前用户的信息
    @GetMapping("/getuserid/{id}")
    public CommonResult getUserById(@PathVariable("id") int id) {
        User user = dao.getUserById(id);
        if (user != null) {
            return CommonResult.success(user);
        } else {
            return CommonResult.fail("User not found");
        }

    }


    @GetMapping("/all")
    public CommonResult getIUser() {
        List<User> list = is.getUser();
        return CommonResult.success(list);
    }

    @PostMapping("/add")
    public CommonResult addUser(@RequestBody User user){
        int count = is.addUser(user);
        if(count>0) {
            return CommonResult.success(count);
        }else {
            return CommonResult.fail();
        }    }

    @PutMapping("/edit/{id}")
    public CommonResult editUser(@PathVariable int id, @RequestBody User user){
        user.setId(id);  // 将URL中的id设置到User对象中
        int count = is.editUser(user);
        if(count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.fail();
        }
    }

    @DeleteMapping("/del/{id}")
    public CommonResult delUser(@PathVariable int id) {
        int count = is.delUser(id);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.fail();
        }
    }

    //  查询商品名或id
    @GetMapping("/search")
    public CommonResult searchUser(@RequestParam String keyword){
        List<User> inventories = is.searchUser(keyword);
        return CommonResult.success(inventories);
    }

    //   分页
    @GetMapping("/paged")
    public CommonResult getPagedUser(@RequestParam int page, @RequestParam int size) {
        List<User> list = is.getPagedUser(page, size);
        int total = is.getTotalUserCount();
        return CommonResult.success(list, total);
    }


}
